package edu.jmu.transmissionassistant.component

import edu.jmu.transmissionassistant.model.UploadFileInfo
import java.util.concurrent.ArrayBlockingQueue
import java.util.concurrent.BlockingQueue
import java.util.concurrent.ConcurrentHashMap

class MessageBus {
    companion object {
        private var mInstance: MessageBus? = null

        fun instance(): MessageBus {
            if (mInstance == null) {
                mInstance = MessageBus()
            }
            return mInstance!!
        }
    }

    private val map: MutableMap<String, BlockingQueue<UploadFileInfo>> = ConcurrentHashMap()

    fun register(name: String) {
        if (map.containsKey(name)) {
            return
        } else {
            map[name] = ArrayBlockingQueue(3)
        }
    }

    fun unregister(name: String) {
        if (map.containsKey(name)) {
            map[name]!!.clear()
            map.remove(name)
        }
    }

    /**
     * <b>WARN:</b>May block thread
     *
     * @throws IllegalAccessException if name hasn't been registered
     */
    fun publish(name:String, value: UploadFileInfo) {
        if (map.containsKey(name)) {
            val que = map[name]!!
            que.offer(value)
        }
        throw IllegalAccessException("$name didn't register yet, register it first")
    }

    /**
     * <b>WARN:</b>Will block thread
     *
     * @throws IllegalAccessException if name hasn't been registered
     */
    fun subscribe(name: String): UploadFileInfo {
        if (map.containsKey(name)) {
            val que = map[name]!!
            return que.take()
        }
        throw IllegalAccessException("$name didn't register yet, register it first")
    }
}